// 获取标签
const go_login = document.querySelector('.go_login')
const logout = document.querySelector('.logout')
const go_cart = document.querySelector('.go_cart')
const loginDiv = document.querySelector('.login')
const nickDiv = document.querySelector('.nick')
const nickP = document.querySelector('.nickP')

const login = window.localStorage.getItem('login')
const nick = window.localStorage.getItem('nick')
const id = window.localStorage.getItem('id')

nickHtml()
function nickHtml() {
    if (!login) {
        loginDiv.classList.add('active')
        return
    }
    nickDiv.classList.add('active')

    // 登录过将用户名写入
    nickP.innerText = 'hello ' + nick
}

// 给帮助中心添加鼠标移入事件,移入时给盒子添加类名让其显示
$('.help').mouseover(function () {
    $('.help_box').stop().slideDown(300, 'linear')//.addClass('active')
})
$('.help').mouseout(function () {
    $('.help_box').stop().slideUp(300, 'linear')//.addClass('active')
})

// 在线咨询
$('.consult').mouseover(function () {
    $(this).addClass('active')
    console.log($(this))
})
$('.consult').mouseout(function () {
    $(this).removeClass('active')
})

// 登录注册下滑盒子
$('.login').mouseover(function () {
    $('.login_box').stop().slideDown(500, 'linear')
})
$('.login').mouseleave(function () {
    $('.login_box').stop().slideUp(500, 'linear')
})
// 注销登录盒子的显示
$('.nick').mouseover(function () {
    $('.nick_box').stop().slideDown(500, 'linear')
})
$('.nick').mouseleave(function () {
    $('.nick_box').stop().slideUp(500, 'linear')
})

// 登录事件
go_login.addEventListener('click', () => {
    window.location.href = './login.html'
})

// 注销绑定事件
logout.onclick = () => {
    window.localStorage.removeItem('id')
    window.localStorage.removeItem('login')
    window.localStorage.removeItem('nick')
    nickDiv.classList.remove('active')
    loginDiv.classList.add('active')
}



// 跳转购物车
go_cart.onclick = function () {
    if (!login) {
        alert('您还没有登录哦,请先登录吧^_^')
        window.location.href = './login.html'
        return
    }
    window.location.href = './cart.html'
}

// 返回首页
const go_index = document.querySelector('.go_index')
go_index.onclick = () => {
    window.location.href = './index.html'
}

// 二级菜单
// 获取li的index,上边ul的li索引-1对应的是下边要显示的li
$('.nav_box>li').mouseover(function () {
    const index = $(this).index()
    let i = index - 1
    if (i >= 0) {
        $('.header_box>li').eq(i).finish().slideDown(300, 'linear').siblings().finish().slideUp(0)
    }
})
$('.header_box').mouseleave(function () {
    $('.header_box>li').finish().slideUp(0)
})


$('.search').mouseover(function () {
    $('.search_inpbox').stop().slideDown(500, 'linear')//.addClass('active')
})
$('.search').mouseout(function () {
    $('.search_inpbox').stop().slideUp(500, 'linear')//.addClass('active')
})
// 搜索引擎
// 获取标签
const searchInp = document.querySelector('.search_inp input')
const ul = document.querySelector('.search_inp ul')

searchInp.oninput = function () {

    const text = this.value.trim()
    const script = document.createElement('script')

    script.src = `https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=34305,34099,33970,34273,34278,34004,34281,34107,34111,26350,22159&wd=${text}&req=2&csor=2&cb=fn&_=1627023610785`
    document.body.appendChild(script)

    script.remove()
}

function fn(res) {

    console.log(res)

    if (!res.g) {
        // 说明没有 g 这个数组
        ul.classList.remove('active')
        return
    }

    let str = ''
    res.g.forEach(item => {
        str += `<li>${item.q}</li>`
    })

    ul.innerHTML = str

    ul.classList.add('active')
}
// 给返回顶部的图片添加事件
const back = document.querySelector('.back')
window.addEventListener('scroll', function () {
    const scrollTop = document.documentElement.scrollTop
    if (scrollTop >= 300) {
        back.classList.add('active')
    } else {
        back.classList.remove('active')
    }
})

// 获取数据进行渲染
const productId = window.localStorage.getItem('product_id')
const detail_box = document.querySelector('.detail_box')

// 发送请求
const xhr = new XMLHttpRequest
xhr.open('POST', '/hln')
xhr.onload = () => bindHtml(xhr)
xhr.setRequestHeader('content-type', 'application/json')
xhr.send('{"addedCategoryCode": "bros_skincare","channelCode": "BROS","filterCategoryCode": [["bros_skincare"]],"filterMainCategoryCode": "bros_skincare","page": 0,"searchCategoryCode": "bros_skincare","sortField": "","sortOrder": ""}');

function bindHtml(xhr) {
    const res = JSON.parse(xhr.responseText)
    const list = res.serializableData.aggResult.productList
    let arr = []
    let str = ''
    list.forEach(item => {
        if (item.id === productId) {
            arr.push(item)
        }
    })
    arr.forEach(item => {
        str = `
        <div class="det_l">
      <ul class="del_listbox">
        <li class="list_img active">
          <img data-url="${item.productImages[0]}" src="${item.productImages[0]}" alt="">
        </li>
        <li class="list_img">
          <img data-url="${item.productImages[1]}" src="${item.productImages[1]}" alt="">
        </li>
        <li class="list_img">
          <img data-url="${item.productImages[2]}" src="${item.productImages[2]}" alt="">
        </li>
        <li class="list_img">
          <img data-url="${item.productImages[3]}" src="${item.productImages[3]}" alt="">
        </li>
      </ul>
      <div class="show">
        <img src="${item.productImages[0]}" alt="">
        <div class="mask"></div>
        <div class="enlarge" style="background-image:url('${item.productImages[0]}');"></div>
      </div>
    </div>
    <div class="det_r">
      <p class="det_p1">${item.productName}</p>
      <p class="det_p2">${item.productNameEn}</p>
      <div class="det_p3">${item.introduction}</div>
      <a href="#" class="det_p4">查看详情</a>
      <div class="det_num">
        <p class="prive"><span class="">￥</span>${(item.defaultPrice).toFixed(2)}</p>
        <div class="num">
          <span>数量</span>
          <div class="buy_num">
            <button class="reduce">-</button>
            <input class="val" data-num="${item.categoryRankNo}" type="text" value="1">
            <button class="add">+</button>
          </div>
        </div>
      </div>
      <select>
        <option value="${item.variantValueList[0]}">${item.variantValueList[0]}</option>
        <option value="${item.variantValueList[1]}">${item.variantValueList[1]}</option>
        <option value="${item.variantValueList[2]}">${item.variantValueList[2]}</option>
      </select>
      <div class="refer">
        <button data-id="${item.id}" class="buy">加入购物袋</button>
        <button class="close">立即结算</button> 
      </div>
      <p class="go_list">返回商品列表</p>
    </div>
        `
    })
    detail_box.innerHTML = str

    // 获取标签添加事件
    const buy_num = document.querySelector('.buy_num')
    const buy = document.querySelector('.buy')
    let num
    let sum
    buy_num.addEventListener('click', e => {
        e = e || window.event
        const target = e.target || e.srcElement
        if (target.className === 'reduce') {
            // 获取value值
            num = target.nextElementSibling.value-0
            if (num <= 1) return
            num--
            target.nextElementSibling.value = num
        }
        if (target.className === 'add') {
            num = target.previousElementSibling.value-0
            
            sum = target.previousElementSibling.dataset.num
            if (num >= sum) return
            num++
            target.previousElementSibling.value = num
            console.log(num)
            console.log(target.previousElementSibling.value)
        }
    })

    const valInp = document.querySelector('.val')
    const refer = document.querySelector('.refer')
    refer.addEventListener('click',e => { 
        e = e || window.event
        const target = e.target || e.srcElement
        // 加入购物车
        // 获取login 没有的话代表没有登陆过 需要先登录
        if (target.className === 'buy') {
            const login = window.localStorage.getItem('login')
            if (!login) {
                window.localStorage.setItem('url','detail')
                window.location.href = './login.html'
                return
            }
            const goodsId = target.dataset.id
            var cartList = list.find(function (item) { return item.id === goodsId })

            var list1 = JSON.parse(window.localStorage.getItem('cart')) || []
            console.log(typeof (list1))

            const cart_number = valInp.value-0

            if (!list1.length) {
                console.log(111)
                cartList.cart_number = cart_number
                cartList.check=false
                list1.push(cartList)
            } else {
                console.log(222)
                var res = list1.some(function (item) { return item.id === goodsId })
                if (res) {
                    var index = list1.findIndex(function (item) { return item.id === goodsId })
                    list1[index].cart_number += cart_number
                    list1[index].check=false
                } else {
                    cartList.cart_number = cart_number
                    cartList.check=false
                    list1.push(cartList)
                }
            }
            window.localStorage.setItem('cart', JSON.stringify(list1))
            alert('加入购物车成功')
        }
        
    })



    const go_list = document.querySelector('.go_list')
    go_list.onclick = () => {
        window.location.href = './list.html'
    }


    // 放大镜效果
    // 获取盒子
    const show = document.querySelector('.show')
    const mask = document.querySelector('.mask')
    const enlarge = document.querySelector('.enlarge')

    // 获取遮罩层的宽高
    const mask_width = parseInt(window.getComputedStyle(mask).width)
    const mask_height = parseInt(window.getComputedStyle(mask).height)

    // 获取显示盒子的宽高
    const show_width = show.offsetWidth
    const show_height = show.offsetHeight

    // 获取背景图的大小
    bg_width = parseInt(window.getComputedStyle(enlarge).backgroundSize.split(' ')[0])
    bg_height = parseInt(window.getComputedStyle(enlarge).backgroundSize.split(' ')[1])

    // 计算放大盒子的宽高
    enlarge_width = bg_width * mask_width / show_width
    enlarge_height = bg_height * mask_height / show_height

    enlarge.style.width = enlarge_width + 'px'
    enlarge.style.height = enlarge_height + 'px'

    // 添加鼠标移入移出效果
    show.addEventListener('mouseover', function () {
        mask.style.display = 'block'
        enlarge.style.display = 'block'
    })
    show.addEventListener('mouseleave', function () {
        mask.style.display = 'none'
        enlarge.style.display = 'none'
    })

    // 添加切换图片效果
    // 获取图片盒子
    const del_listbox = document.querySelector('.del_listbox')
    del_listbox.addEventListener('click', e => {
        e = e || window.event
        const target = e.target || e.srcElement
        if (target.nodeName === 'IMG') {
            const url = target.dataset.url
            show.firstElementChild.src = url
            enlarge.style.backgroundImage = `url(${url})`
        }
        for (let i = 0; i < del_listbox.children.length; i++) {
            del_listbox.children[i].classList.remove('active')
        }
        target.parentElement.classList.add('active')
    })

    // 计算鼠标的位置
    show.addEventListener('mousemove', e => {
        e = e || window.event

        let x = e.offsetX - mask_width / 2
        let y = e.offsetY - mask_height / 2

        x = x < 0 ? 0 : x
        y = y < 0 ? 0 : y

        x = x >= show_width - mask_width ? show_width - mask_width : x
        y = y >= show_height - mask_height ? show_height - mask_height : y

        mask.style.left = x + 'px'
        mask.style.top = y + 'px'

        bgx = x * enlarge_width / mask_width
        bgy = y * enlarge_width / mask_width
        enlarge.style.backgroundPosition = `-${bgx}px -${bgy}px`
    })

}

